package yxy.game.pm2.module.matchonline;

import org.joda.time.DateTime;
import org.redisson.api.RList;
import org.redisson.api.RQueue;
import yxy.apple.util.redisson.RedisConnection;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.data.bean.matchonlinedata;
import yxy.cherry.game.base.redis.RedisManager;
import yxy.cherry.game.base.redis.RedisType;
import yxy.game.pm2.bean.Format;
import yxy.game.pm2.bean.db.dao.MySQLCacheDAO;
import yxy.game.pm2.bean.module.PlayerModule;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static yxy.cherry.data.DataCenter.getAllData;


//在线匹配玩家类
public class MatchOnlinePlayerModule extends PlayerModule {

    public static String redisQuene = "MATCHPLAYER_QUEUE";  //匹配的队列
    public static int winRewardNum = 20;                   //胜利的奖励元宝
    public static int winMaxTimes = 12;                   //最高获胜次数
    public static int failMaxTimes = 3;                   //最高失败次数

    // bean===========================================================================

    private Format format;          //阵容
    private int winTimes;           //胜利次数（当前这次入场）
    private int failTimes;          //失败次数（当前这次入场）
    private int[] selectIdList;     //选择的武将集合（6轮选择武将，每轮会提供3个，选其中一个）
    private int status;             //状态  0 正在匹配  1 取消匹配  2 结束状态
    private int passMaxWinTimes;   //历史最高胜利次数
    private int twentyOneHeroNum  ;//21资质的武将数量
    private DateTime updateTime;   //更新时间

    public int getTwentyOneHeroNum() {
        return twentyOneHeroNum;
    }

    public void setTwentyOneHeroNum(int twentyOneHeroNum) {
        this.twentyOneHeroNum = twentyOneHeroNum;
    }

    public Format getFormat() {
        return format;
    }

    public void setFormat(Format format) {
        this.format = format;
    }

    public int getWinTimes() {
        return winTimes;
    }

    public void setWinTimes(int winTimes) {
        this.winTimes = winTimes;
    }

    public int getFailTimes() {
        return failTimes;
    }

    public void setFailTimes(int failTimes) {
        this.failTimes = failTimes;
    }

    public int[] getSelectIdList() {
        return selectIdList;
    }

    public void setSelectIdList(int[] selectIdList) {
        this.selectIdList = selectIdList;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public int getPassMaxWinTimes() {
        return passMaxWinTimes;
    }

    public void setPassMaxWinTimes(int passMaxWinTimes) {
        this.passMaxWinTimes = passMaxWinTimes;
    }

    public DateTime getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(DateTime updateTime) {
        this.updateTime = updateTime;
    }
    // func===========================================================================

    public static MatchOnlinePlayerModule create(String playerCode) {
        MatchOnlinePlayerModule module = new MatchOnlinePlayerModule();
        module.setStatus(2);
        module.setPlayerCode(playerCode);
        module.setUpdateTime(DateTime.now());
        module.set();
        return module;
    }

    //消耗物品 记录重置
    public void reset(int status) {
        //记录到机器人列表
        if (status == 2) {
            int winTimes = getWinTimes();//获胜次数
            saveToMachine(winTimes);
        }

        setTwentyOneHeroNum(0);
        setWinTimes(0);
        setFailTimes(0);
        initSelectHeroList();
        setStatus(status);
        setFormat(null);
        setUpdateTime(DateTime.now());
        set();
    }

    //保存到机器人列表
    public void saveToMachine(int winTimes) {
        RList<MatchOnlineMachine> list = MatchOnlineMachine.get(winTimes);
        MatchOnlineMachine machine = new MatchOnlineMachine();
        machine.setFormat(getFormat());
        machine.setPlayerCode(getPlayerCode());
        Boolean isAddToList = true;
        //已存在该玩家则不再添加进缓存
        for (MatchOnlineMachine onlineMachine : list) {
            if (onlineMachine.getPlayerCode().equals(getPlayerCode())) {
                isAddToList = false;
                break;
            }
        }
        if (isAddToList) {
            MatchOnlineMachine.add(winTimes,machine);
        }
    }


    //todo 重置可选武将信息
    public void initSelectHeroList() {

        MatchOnlineHandle handle = new MatchOnlineHandle();

        int[] heros = handle.getSelectHero(this);

        setSelectIdList(heros);
    }

    // redis==========================================================================

    static protected RedisConnection redis2() {
        return RedisManager.getInstance().getConnection(RedisType.REDIS_DATA);
    }

    static public RQueue<QueuePlayerInfo> getQueue() {

        RedisConnection connection = redis2();

        RQueue<QueuePlayerInfo> queue = connection.client().getQueue(redisQuene);

        return queue;
    }


    private static String key(String playerCode) {
        return String.format("PLAYER:%s:MODULE:MATCHONLINE", playerCode);
    }


    public void set() {
        try {
            setv(key(getPlayerCode()), this);
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }

    static public MatchOnlinePlayerModule get(String playerCode) {
        try {
            MatchOnlinePlayerModule module = getv(key(playerCode));
            //todo 后期放数据库
            if (module == null) {
                module = MySQLCacheDAO.getV(key(playerCode), MatchOnlinePlayerModule.class);
                if (module != null) {
                    module.set();
                }//把数据同步到redis
            }
            if (module == null) {
                module = create(playerCode);
            }

            module.update();
            return module;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public void update() {

    }

    //存储到数据库的方法
    public static void saveToDB(String playerCode) {
        try {
            String key = key(playerCode);
            if (touchBucket(key).isExists()) {
                MatchOnlinePlayerModule module = getv(key(playerCode));
                if (module != null) MySQLCacheDAO.setV(key, module);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //从redis移走数据的操作
    public static void removeAllFromRedis(String playerCode) {
        try {
            touchBucket(key(playerCode)).delete();
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }

    // lock==========================================================================

    static public String lockKey(String playerCode) {
        return String.format("lock:%s", key(playerCode));
    }

    @Override
    public String lockKey() {
        return String.format("lock:%s", key(getPlayerCode()));
    }
}
